import { ActionSheetController, AlertController, LoadingController, ModalController, Platform } from '@ionic/angular';
import { ChangeDetectorRef, Component, ElementRef, Input, OnInit, ViewChild } from '@angular/core';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { HttpService } from 'src/app/shared/service/http.service';
import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { VideoImgPopupComponent } from '../video-img-popup/video-img-popup.component';
import { EventService } from 'src/app/shared/service/event.service';
import { Camera } from '@ionic-native/camera/ngx';
import { UploadImageService } from 'src/app/shared/service/uploadImageService';
@Component({
  selector: 'app-video-comments-details',
  templateUrl: './video-comments-details.component.html',
  styleUrls: ['./video-comments-details.component.scss'],
})
export class videoCommentsDetailsComponent implements OnInit {
  @Input() tagData: any = {};
  @ViewChild('myTextarea', { read: ElementRef }) myTextareaRef: ElementRef;
  showLoadMore = false;
  pageNo = 1;
  pageSize: number;
  pageTotal: number;
  // 筛选及页面数据参数
  params: any = { content: {} };
  sendLabelValue: any;
  noShowFootBtn = true;
  timer: any;
  phoneArray: any;
  index: any;
  data: any;
  selectImg: any;
  maxSize = 1;
  isNative: boolean;
  currentTime: string;
  focusItem: any;
  loginHandler = this.appGlobalService.debounce((data2: any) => {
    this.pageModalService.openPage(this.appGlobalService.popUpLoginLink);
  }, 300);
  canSend: boolean;
  constructor(
    private pageModalService: PageModalService,
    private appGlobalService: AppGlobalService,
    public alertController: AlertController,
    private httpService: HttpService,
    public modalController: ModalController,
    public eventService: EventService,
    private platform: Platform,
    private camera: Camera,
    private uploadImageService: UploadImageService,
    private loadingController: LoadingController,
    private ref: ChangeDetectorRef,
    private actionSheetCtrl: ActionSheetController,

  ) { }

  ngOnInit() {

    this.pageTotal = this.tagData.pageTotal;
    this.pageNo = this.tagData.pageNo;
    this.pageSize = this.tagData.pageSize;
    this.params.content = this.tagData.data.submit;
    this.params.sessionId = localStorage.getItem("sessionId");
    // tslint:disable-next-line: max-line-length
    this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize));

    this.tagData.data.data.forEach(element => {
      if (element.firstRowLeft && element.firstRowLeft.secondText && element.firstRowLeft.secondText.subSecondData) {
        element.firstRowLeft.secondText.subSecondDataSlice = [];
        element.firstRowLeft.secondText['saveSubSecondData'] = Array.from(element.firstRowLeft.secondText.subSecondData);
        element.firstRowLeft.secondText['subSecondDataLength'] = element.firstRowLeft.secondText.subSecondData.length;
        if (element.firstRowLeft.secondText.subSecondData.length > 4) {
          element.firstRowLeft.secondText.showReplies = `展开${element.firstRowLeft.secondText.subSecondData.length}条回复`;
          element.firstRowLeft.secondText.pageNo = 0;
        } else if (element.firstRowLeft.secondText.subSecondData.length > 0) {
          element.firstRowLeft.secondText.showReplies = `展开${element.firstRowLeft.secondText.subSecondData.length}条回复`;
        }
      }
    });

    if (this.tagData.data.data.length > 0) {
      this.appGlobalService.videoDetailsData = this.tagData.data.data[0];
    }

    if (this.eventService.eventEmit.listenerCount('videosDetails_dataItem') > 0) {
      this.eventService.eventEmit.removeListener('videosDetails_dataItem');
    }
    this.eventService.eventEmit.on("videosDetails_dataItem", r => {
      console.log(r);
      const page: any = this.appGlobalService.targetObj;
      page.params.user_msg_video_id = r.id;
      let tag_data = this.tagData.data.data;
      this.httpService.post('application/page', page, async res => {
        const tagData = JSON.parse(res.script).views[0].tags;
        tagData.forEach(element => {
          if (element.style === 'videoDetailsTag' && element.data && element.data.data[0]) {
            let el_data = element.data.data; // 保存element.data.data
            if (r.type && r.type === '0') {
              el_data.forEach(e => {
                if (r.id === e.id) {
                  if (tag_data.length === 0) {
                    tag_data.push(e);
                  } else {
                    tag_data = this.customUnshift(tag_data, e);
                    document.getElementById('data').scrollTo({ top: 0, behavior: 'auto' });
                  }
                }
              });

            } else if (r.type && r.type === '1') {
              el_data.forEach(e => {
                if (e.id === tag_data[this.index].id) {
                  e.firstRowLeft.secondText.subSecondData.forEach(element => {
                    if (r.id === element.son_id) {
                      if (tag_data[this.index].firstRowLeft.secondText.subSecondData && tag_data[this.index].firstRowLeft.secondText.subSecondData.length === 0) {
                        tag_data[this.index].firstRowLeft.secondText.subSecondData = e.firstRowLeft.secondText.subSecondData;
                        tag_data[this.index].firstRowLeft.secondText.subSecondDataSlice =  Array.from(e.firstRowLeft.secondText.subSecondData);
                        tag_data[this.index].firstRowLeft.secondText.subSecondDataLength = 1;
                      } else if (tag_data[this.index].firstRowLeft.secondText.subSecondData.length > 0) {

                        tag_data[this.index].firstRowLeft.secondText.subSecondDataSlice = this.customUnshift(
                          tag_data[this.index].firstRowLeft.secondText.subSecondDataSlice,
                          element
                        );
      
                        if (tag_data[this.index].firstRowLeft.secondText.subSecondDataLength) {
                          tag_data[this.index].firstRowLeft.secondText.subSecondDataLength += 1;
                        }
      
                        // 添加第二条回复时
                        if (tag_data[this.index].firstRowLeft.secondText.subSecondDataSlice.length
                          && tag_data[this.index].firstRowLeft.secondText
                          && !tag_data[this.index].firstRowLeft.secondText.showReplies) {
                          tag_data[this.index].firstRowLeft.secondText.showReplies = '收起';
                          // 箭头向上
                          tag_data[this.index].firstRowLeft.secondText.arrowIcon = 'https://zeno-img.oss-cn-shenzhen.aliyuncs.com/file_17339032479847969bff8a0e9c3f741c7bcb20079e384.png';
                        }
                      }
                    }
                  });
                }
              });
            }

            this.tagData.data.headDiv.titleNumber = element.data.headDiv.titleNumber;
          }
        });
      });
    });


    this.currentTime = 'time' + Date.now();
    let that = this;
    if (this.platform.is('cordova')) {
      this.isNative = true;
    } else {
      this.isNative = false;
    }
    this.data = this.appGlobalService.videoDetailsData;
    this.tagData.valueArray = [];
    setTimeout(() => {
      document.getElementById('click-img').addEventListener('click', function (e) {
        e.preventDefault();
        let num = 0;
        let domName = 'photo-select-' + that.currentTime;
        while (num < 3) {
          console.log(num);
          num++;
          document.getElementById(domName).click();
        }
      });
    }, 200);
  }
  customUnshift(array, ...elements) {
    // 创建一个新的数组来存储结果
    let newArray = [];

    // 遍历传入的元素，并将它们添加到新数组的开头
    for (let i = 0; i < elements.length; i++) {
      newArray.push(elements[i]);
    }

    // 遍历原始数组，将其元素添加到新数组中
    for (let i = 0; i < array.length; i++) {
      newArray.push(array[i]);
    }

    // 如果需要修改原数组，可以将新数组的元素复制回原数组
    for (let i = 0; i < newArray.length; i++) {
      array[i] = newArray[i];
    }

    // 如果不需要修改原数组，可以直接返回新数组
    return newArray;

  }
  loadMoreData(event) {
    try {
      this.params = { content: {} };
      this.params = this.tagData.data.submit;
      this.pageNo = this.pageNo + 1;
      // // 参数
      this.params.content.pageNo = this.pageNo;
      this.params.id = this.tagData.data.submit.id;
      this.params.sessionId = localStorage.getItem("sessionId");
      // 请求获取新数据
      this.httpService.post('application/submit', this.params, res => {

        // 请求数据成功
        if (res.success) {
          if (res.data.submit) {
            this.params = res.data.submit; // 为了每次刷新下一页的参数 "oldIndex"
          }
          res.data.data.forEach(element => {
            if (element.firstRowLeft && element.firstRowLeft.secondText && element.firstRowLeft.secondText.subSecondData) {
              element.firstRowLeft.secondText.subSecondDataSlice = [];
              element.firstRowLeft.secondText['saveSubSecondData'] = Array.from(element.firstRowLeft.secondText.subSecondData);
              element.firstRowLeft.secondText['subSecondDataLength'] = element.firstRowLeft.secondText.subSecondData.length;
              if (element.firstRowLeft.secondText.subSecondData.length > 4) {
                element.firstRowLeft.secondText.showReplies = `展开${element.firstRowLeft.secondText.subSecondData.length}条回复`;
                element.firstRowLeft.secondText.pageNo = 0;
              } else {
                element.firstRowLeft.secondText.showReplies = `展开${element.firstRowLeft.secondText.subSecondData.length}条回复`;
              }
            }
          });
          const resList = res.data.data;
          // 追加返回数据
          if (resList && resList.length > 0) {
            // 追加数据
            resList.map(v => {
              this.tagData.data.data.push(v);
            });
          } else {
            event.target.disabled = true;
            this.showLoadMore = false;
          }
        } else {
          // 请求失败，更新当前页数
          this.pageNo = this.pageNo - 1;
          // 请求数据失败
          // this.appGlobalService.showToast(res.message, 2000, 'middle');
        }
        event.target.complete();

      }, err => {
        // 请求失败，更新当前页数
        this.pageNo = this.pageNo - 1;
        // 请求数据失败
        // this.appGlobalService.showToast(err.message, 2000, 'middle');
        event.target.complete();

      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }

  showAll(item) {
    item.show = !item.show;
    if (item.show) {
      item.showText = '收起';
    } else {
      item.showText = '查看全部';
    }
  }

  openImg(img, i) {
    let imgs = [img];
    this.pageModalService.openImage_url(i, imgs);
  }

  async popup(data) {
    const modal = await this.modalController.create({
      component: VideoImgPopupComponent,
      componentProps: { tagData: data, style: this.tagData.style }
    });
    return await modal.present();

  }

  careBtn(item) {
    const params = {
      content: item.submit.content,
      id: item.submit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.post("application/submit", params, res => {
      if (res.success) {
        if (res.data && res.data.eventResult !== undefined && res.data.eventResult === 'true') {
          item.state = '1';
          item.label = '已关注';
        } else if (res.data && res.data.eventResult !== undefined && res.data.eventResult === 'false') {
          item.state = '0';
          item.label = '关注';
        }
      }
    });
  }

  openPage(link, e?) {
    if (e) {
      e.stopPropagation();
    }
    if (link) {
      this.pageModalService.openPage(link);
    }
  }

  LookReplies(e, item, i) {
    e.stopPropagation();
    if (item.showReplies !== '收起') {
      if (item.pageNo !== undefined && item.pageNo !== '') {
        let arr = item.saveSubSecondData.slice(item.pageNo * 5, (item.pageNo * 5 + 5));
        // 记录原数组长度
        if (item.subSecondDataSlice) {
          item.subSecondDataSlice = item.subSecondDataSlice.concat(arr);
        } else {
          item.subSecondDataSlice = arr;
        }
        if (item.subSecondDataSlice.length === item.subSecondDataLength) {
          item.showReplies = '收起';
          // 箭头向上
          item.arrowIcon = 'https://zeno-img.oss-cn-shenzhen.aliyuncs.com/file_17339032479847969bff8a0e9c3f741c7bcb20079e384.png';
        } else {
          item.pageNo += 1;
          item.showReplies = `展开更多`;
        }
      } else {
        // 说明初始回复数量不到5条
        if (item.subSecondDataSlice && item.subSecondDataSlice.length > 0) {
          item.subSecondDataSlice = item.subSecondDataSlice.concat(item.subSecondData);
        } else {
          item.subSecondDataSlice = Array.from(item.subSecondData);
        }
        item.showReplies = '收起';
        // 箭头向上
        item.arrowIcon = 'https://zeno-img.oss-cn-shenzhen.aliyuncs.com/file_17339032479847969bff8a0e9c3f741c7bcb20079e384.png';
      }
    } else {
      item.subSecondData = Array.from(item.subSecondDataSlice); // 说明评论已全部展开
      item.saveSubSecondData =  Array.from(item.subSecondData);
      item.showReplies = `展开${item.subSecondData.length}条回复`;
      item.subSecondDataLength = item.subSecondData.length;
      item.subSecondDataSlice = [];
      item.pageNo = 0;
      // 箭头向下
      item.arrowIcon = 'https://zeno-img.oss-cn-shenzhen.aliyuncs.com/file_173390330175828ed961032df2d6a0640ad5a734745b0.png';
    }

  }

  async btnClick(item, data?, i?, leftItem?) {
    const that = this;
    this.index = i;
    if (item.type && item.type === 'iconDelete') {
      // 删除
      this.deleteItem(item.msg, item, data, i);
    } else if ((item.type && item.type === 'iconSubmit') || (item.submit && item.submit.id === "likeContent")) {
      // 点赞
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {

          if (res.target && res.skip) {
            let type = res.type ? res.type : 'page';
            if (res.skip === 1) {
              type = 'page';
              // tslint:disable-next-line:no-shadowed-variable
              const link = {
                type,
                target: res.target,
                params: res.params ? res.params : {}
              };
              this.pageModalService.openPage(link);

            } else if (res.skip === 4) {
              type = 'pageModal';
              if (this.appGlobalService.popUpLoginLink) {
                this.loginHandler(res);
                return;
              }

            }

          } else if (res.data && res.data.eventResult !== undefined) {
            if (res.data.eventResult === "false") {
              item.icon_status = 0;
              // tslint:disable-next-line:no-unused-expression
              leftItem && leftItem.likeContent ? leftItem.icon_status = 0 : '';

              if (item.value > 0) {
                item.value = Number(item.value) - 1;
              } else if (isNaN(item.value)) {
                item.value = 0;
              }

              if (leftItem && leftItem.like > 0) {
                leftItem.like = Number(leftItem.like) - 1;
              } else if (isNaN(leftItem && leftItem.like)) {
                leftItem.like = 0;
              }
            } else if (res.data.eventResult === "true") {
              item.icon_status = 1;
              leftItem && leftItem.likeContent ? leftItem.icon_status = 1 : '';
              item.value = Number(item.value) + 1;

              leftItem && leftItem.likeContent ? leftItem.like = Number(leftItem.like) + 1 : '';

            }
          }
        }
      });
      return;
    } else if ((item.type && item.type === "iconRemove") || (item.submit && item.submit.id === "deleteContent")) {
      // 删除·不做提示
      if (item.submit) {
        const params = {
          content: item.submit.content,
          id: item.submit.id,
          sessionId: localStorage.getItem("sessionId")
        };
        this.httpService.post("application/submit", params, res => {
          if (res.success) {
           
            console.log('删除展示数组元素', data[i]['son_id']);

            if (leftItem && leftItem.subSecondData && leftItem.subSecondData.length > 0) {
              for (let index = 0; index < leftItem.subSecondData.length; index++) {
                if (data[i]['son_id'] === leftItem.subSecondData[index]['son_id']) {
                  console.log('删除原数组元素', leftItem.subSecondData[index]['son_id']);
                  leftItem.subSecondData.splice(index, 1);
                  break;
                }
              }
            }
            if (leftItem && leftItem['subSecondDataLength'] && leftItem.subSecondDataLength > 0) {
              leftItem.subSecondDataLength -= 1;
            }
            data.splice(i, 1);
            console.log(leftItem.subSecondData, leftItem.subSecondDataSlice); // 删除后

            if (item.type && item.type === "iconRemove" && this.tagData.data && this.tagData.data.headDiv && this.tagData.data.headDiv.titleNumber && this.tagData.data.headDiv.titleNumber > 0) {
              this.tagData.data.headDiv.titleNumber -= 1;
            }

            if (item.type && item.type === "iconRemove" && (this.sendLabelValue || this.tagData.data.footDiv.firstRowRight.firstText.img)) {
              if (this.focusItem && this.focusItem.submit.content.type === '1' && this.focusItem['index'] === i) {
                this.focusItem = this.tagData.data.footDiv.firstRowRight;
              }
            }
          }
          this.appGlobalService.showToast(res.message, 1500, 'middle');
        });
      }
    } else if ((item.type && item.type === "iconSendLabel") || (item.submit && item.submit.id === "replyContent")) {
      // 评论 视频评论弃用
      if (item.link) {
        await this.openPage(item.link);
      }
      this.appGlobalService.sendLabelMsg = item.submit;

    } else if (item.type && item.type === 'iconCareBtn') {
      // 点关注按钮
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        if (res.success) {
          if (res.data && res.data.eventResult !== undefined) {
            if (res.data.eventResult === "false") {
              item.label = '关注';
              data.forEach(e => {
                if (e.firstRowRight.singleText &&
                  item.submit.content.interest_user_id === e.firstRowRight.singleText.submit.content.interest_user_id) {
                  e.firstRowRight.singleText.label = '关注';
                }
              });

            } else if (res.data.eventResult === "true") {
              item.label = '已关注';
              data.forEach(e => {
                if (e.firstRowRight.singleText &&
                  item.submit.content.interest_user_id === e.firstRowRight.singleText.submit.content.interest_user_id) {
                  e.firstRowRight.singleText.label = '已关注';
                }
              });
            }
          }
        }
        this.appGlobalService.showToast(res.message, 1500, "middle");
      });
    } else if (item.type && item.type === "iconLink") {
      if (item.link.type && item.link.type === 'chat') {//

        if (item.link.params !== undefined && item.link.params.chatId !== undefined) {
          this.httpService.gotoChat(item, item.link.params.chatId);

        } else {
          this.httpService.gotoChat(item);
        }
      } else {
        this.openPage(item.link)
      }
    } else if (item.type && item.type === "phone") {
      this.phoneArray = item.phone.split(",");
      this.presentAlertConfirm(Number(this.phoneArray[0]), item.name);
    }
  }

  // 删除
  async deleteItem(msg, item, data, index) {
    const alert = await this.alertController.create({
      header: '',
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "确定",
          handler: () => {
            if (item && item.submit) {
              const params = {
                content: item.submit.content,
                id: item.submit.id,
                sessionId: localStorage.getItem("sessionId")
              };
              this.httpService.post("application/submit", params, res => {
                if (res.success) {
                  data.splice(index, 1);
                }
                this.appGlobalService.showToast(res.message, 1500, 'middle');
              });
            }
          }
        }
      ]
    });
    alert.present();
  }

  async presentAlertConfirm(mobile, name?) {
    const msg = (name ? name + ' ' : '') + mobile;
    const alert = await this.alertController.create({
      header: this.tagData.nickName,
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "拨打",
          handler: () => {
            this.httpService.changeCallNumber(mobile);
          }
        }
      ]
    });

    await alert.present();
  }

  del(item, data, index) {
    if (item && item.submit) {
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        if (res.success) {
          data.splice(index, 1);
        }
        this.appGlobalService.showToast(res.message, 1500, 'middle');
      });
    }
  }

  async closeModal() {
    const modal = await this.modalController.getTop();
    if (modal !== undefined) {
      modal.dismiss({ data: this.tagData.data.headDiv.titleNumber });
    }
  }

  ionFocus(e) {
    e.stopPropagation();
    console.log('获取焦点');
    if (!localStorage.getItem('loginStatus')
      || (localStorage.getItem('loginStatus')
        && localStorage.getItem('loginStatus') === 'false')) {
      // 这意味着如果这个函数在300毫秒内被多次触发，只有最后一次触发会在300毫秒后执行
      if (this.appGlobalService.popUpLoginLink) {
        this.loginHandler(e);
        return;
      }
    }
  }

  ionBlur(e) {
    e.stopPropagation();
    console.log('失去焦点');
    if (this.sendLabelValue === ''
      && (this.tagData.data.footDiv.firstRowRight.firstText.img === ''
        || this.tagData.data.footDiv.firstRowRight.firstText.img === undefined)) {
      this.focusItem = '';
    }
  }

  ionChange(e) {
    e.stopPropagation();
    setTimeout(() => {
      if (this.noShowFootBtn !== false && this.sendLabelValue !== '') {
        this.noShowFootBtn = false;
      } else if (this.noShowFootBtn !== false && this.tagData.data.footDiv.firstRowRight.firstText.img !== '') {
        this.noShowFootBtn = false;
      }
    }, 200);

    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      this.sendLabelValue = e.detail.value;
      if (this.sendLabelValue === '' && (this.tagData.data.footDiv.firstRowRight.firstText.img === '' || this.tagData.data.footDiv.firstRowRight.firstText.img === undefined)) {
        setTimeout(() => {
          this.noShowFootBtn = true;
        }, 100);
      }
    }, 100);
  }

  sendLabel(e, itemData) {
    if (this.canSend === false){
     return; 
    }
    this.canSend = false;
    let item;
    if (this.focusItem && this.sendLabelValue) {
      item = this.focusItem;
    } else {
      item = itemData;
    }
    e.stopPropagation();
    const that = this;
    if (item && item.submit && item.submit.content.label) {
      const itemContent = JSON.parse(JSON.stringify(item.submit.content));
      itemContent[itemContent.label] = this.sendLabelValue;
      itemContent[itemContent.pic_url] = this.tagData.data.footDiv.firstRowRight.firstText.img ? this.tagData.data.footDiv.firstRowRight.firstText.img : '';
      const params = {
        content: itemContent,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.sendLabelValue = '';
      this.tagData.valueArray = [];
      this.tagData.data.footDiv.firstRowRight.firstText.img ? this.tagData.data.footDiv.firstRowRight.firstText.img = '' : '';
      if (this.noShowFootBtn === false) {
        this.noShowFootBtn = true;
      }
      this.httpService.post("application/submit", params, res => {
        if (res.success) {
          if (res.target && res.skip) {
            let type = res.type ? res.type : 'page';
            if (res.skip === 1) {
              type = 'page';
            } else if (res.skip === 4) {
              type = 'pageModal';
            }
            // tslint:disable-next-line:no-shadowed-variable
            const link = {
              type,
              target: res.target,
              params: res.params ? res.params : {}
            };
            this.pageModalService.openPage(link);

          } else {
            if (res.data && res.data.eventResult) {
              this.eventService.eventEmit.emit("videosDetails_dataItem", { id: res.data.eventResult, type: item.submit.content.type });
            }
          }
        }
        this.appGlobalService.showToast(res.message, 1500, 'middle');
        this.focusItem = '';
        this.canSend = true;
      }, err => {
        this.canSend = true;
      });
    }
  }

  // App 上传文件
  async presentAction(i) {
    const that = this;
    {
      const actionSheet = await this.actionSheetCtrl.create({
        mode: 'ios',
        cssClass: 'as_padding as_common as_border_common',
        buttons: [{
          text: '相机',
          cssClass: 'as_font_bd',
          handler: () => {
            const source = this.camera.PictureSourceType.CAMERA;
            this.uploadImageService.takePicture(source, that.tagData.allowEdit, (url) => {

              if (that.tagData.valueArray.length === that.maxSize) {
                that.tagData.valueArray[that.maxSize - 1] = { path: url };
              } else {
                that.tagData.valueArray.push({ path: url });
              }
              that.tagData.data.footDiv.firstRowRight.firstText.img = url;

            }, null);
          }

        }, {
          text: '从手机相册选择',
          cssClass: 'as_font_color',
          handler: () => {

            // 2024.06.14 整合统一从uploadImageService处理

            this.uploadImageService.openImgPicker(
              // tslint:disable-next-line:no-shadowed-variable
              (url: any, fileName: any) => {
                that.hideLoader();
                if (that.tagData.valueArray.length === that.maxSize) {
                  that.tagData.valueArray[that.maxSize - 1] = { path: url };
                } else {
                  that.tagData.valueArray.push({ path: url });
                }
                that.tagData.data.footDiv.firstRowRight.firstText.img = url;
              },
              that.maxSize,
              1,
              null,
              { allowCropper: false }, this.ref);

          }
        },
        {
          text: '取消',
          cssClass: 'as_font_top',
          handler: () => {
            console.log('Cancel clicked');
          }
        }]
      });
      await actionSheet.present();
    }
  }

  // web 上传文件
  uploadFile(event) {
    if (this.tagData.data.footDiv.firstRowRight.firstText.img && this.tagData.valueArray.length > 0) {
      return;
    }

    this.uploadFileForWeb(event);
  }

  uploadFileForWeb(event: any, fileType?: string) {

    const that = this;
    if (event.target.files && event.target.files[0]) {
      this.selectImg = event.target.files[0];
      if (['jpeg', 'png', 'gif', 'jpg', 'mp4', 'pdf'].indexOf(this.selectImg.type.split('/')[1]) > -1) {

        const reader = new FileReader();
        reader.readAsDataURL(that.selectImg);
        reader.onload = (e) => {
          const uploadData = new FormData();
          uploadData.append('file', that.selectImg);

          that.uploadImageService.uploadFileForWeb(this.selectImg, (resUrl: any) => {

            if (that.tagData.valueArray.length === that.maxSize) {
              that.tagData.valueArray[that.maxSize - 1] = { path: resUrl };
            } else {
              that.tagData.valueArray.push({ path: resUrl });
              that.tagData.data.footDiv.firstRowRight.firstText.img = resUrl;
            }
          }, that.tagData.cropperRatio);

        };
      } else {
        this.appGlobalService.showToast('格式不正确，请选择图片', 3000, 'middle');
      }
    }
  }

  hideLoader() {
    const that = this;
    setTimeout(() => {
      if (that.loadingController) {
        that.loadingController.dismiss();
      }
    }, 1000);
  }

  delImg(e) {
    e.stopPropagation();
    this.tagData.data.footDiv.firstRowRight.firstText.img = '';
    this.tagData.valueArray = [];
  }

  // 获取焦点
  focusTextarea(item, data, i, e) {
    this.index = i;
    this.focusItem = '';
    this.focusItem = item;
    this.focusItem['index'] = i;
    if (this.myTextareaRef && this.myTextareaRef.nativeElement) {
      const textareaElement = this.myTextareaRef.nativeElement.querySelector('textarea');
      if (textareaElement) {
        textareaElement.focus(e);
      }
    }
  }
}
